<!--
 * @Author: ckk
 * @Date: 2022-08-16 14:26:14
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-07-21 15:40:57
 * @Description: 同步培优占位
-->
<template>
  <div class="synchronization">
    <div class="sync-top">
      <!-- <img class="studyone" src="../../assets/images/studyone.png" alt=""> -->
      <img :src="datas.setStyle.bgImg" alt="" v-if="datas.setStyle.bgImg">
      <div class="sync-content">
        <div class="catalogue">
          <img src="../../assets/images/mulu.png" alt="" @click="switchDirectories()">
          <span @click="switchDirectories()">切换目录</span>
        </div>
        <div class="course-name">
          {{showCourseObj.parentName}}
        </div>
        <div class="check-course">
          <span>{{showCourseObj.name}}</span>
          <div class="btns">
            <img
              @click="toPerFun"
              :src="!isLeftClick?require('../../assets/images/predisable.png'):require('../../assets/images/pre.png')"
              alt=""
              style="margin-right:2px"
            >
            <img
              @click="toNextFun"
              :src="!isRightClick?require('../../assets/images/disablenext.png'):require('../../assets/images/next.png')"
              alt=""
            >
          </div>
        </div>
        <img class="link" src="../../assets/images/link.png" alt="">
      </div>
    </div>
    <div class="sync-bottom">
      <div class="sync-item" v-for="(item, index) in syncModleList" :key="index">
        <p class="sync-title">{{item.name}}</p>
        <div class="description">
          <div class="description-item" v-for="(ite,ind) in item.moduleList" :key="ind" @click="gotoStudy(ite)">
            <img :src="ite.posterUrl" alt="">
            <p>{{ite.sourceName}}</p>
          </div>
        </div>
      </div>
    </div>
    <!-- 展示目录 -->
    <BookTree
      @onSelect="onTreeSelect"
      @onSwitch="onVersionSwitch"
      @onClose="onDialogClose"
      :cataShow="catalogueshow"
      :currentId="currentId"
      ref="cataDialog">
    </BookTree>
  </div>
</template>

<script>
import { Popup, Toast } from 'yj-mob-ui';
import YouXin from 'youxin-js-sdk';
import { getJsonlocalStore } from '../../common/comfun';
import { findTreeLeaf, findTreeNodeById } from '@/utils/tree';
import throttle from 'lodash/throttle';
import { excellentServices, catalogServices } from '@/api';
import { judgePlay, assemblePlayParams } from '@/utils/play.js';
import { commitTask } from '@/utils/taskCommit';
import local from '@/utils/local.js';
export default {
  name: '',
  components: {
    [Popup.name]: Popup,
    [Toast.name]: Toast,
    BookTree: () => import('../BookThree')
  },
  props: {
    datas: Object
  },
  data () {
    return {
      currentId: '', // 当前进行中的目录id
      syncCatId: '',
      currentPage: 1,
      show: false,
      // showCrouseIndex: 0,
      coursestyleCode: '', // coursestyleCode: '', // 当前科目对应的环节模板样式
      catalogueshow: false, // 目录框
      // 当前用户相关信息
      currentInfo: {
        currentStageCode: '', // 当前学段编码
        currentGradeCode: '', // 当前年级编码
        currentTermCode: '', // 当前学期编码
        currentSubjectCode: '' // 当前学科编码
      },
      showCourseObj: {
        parentName: '',
        name: ''
      },
      couseData: [],
      syncModleList: [],
      // 上一课是否可以点击
      isLeftClick: true,
      // 下一课是否可以点击
      isRightClick: true
    };
  },
  watch: {
    couseData: {
      handler: function (newValue) {
        // this.setCrouseIsClick();
      },
      immediate: true
    },
    currentId: {
      handler: function (newValue) {
        if (newValue) {
          this.syncCatId = newValue;
          this.showCrouseIndex = this.couseData.findIndex(v => v.id === newValue);
          this.showCourseObj = this.couseData[this.showCrouseIndex];
          this.setCrouseIsClick();
        }
      },
      immediate: true
    },
    showCrouseIndex: {
      handler: function (newValue) {
        if (this.couseData.length > 0 && newValue !== undefined && newValue >= 0) {
          this.showCourseObj = this.couseData[this.showCrouseIndex];
          this.currentId = this.couseData[this.showCrouseIndex].id;
        }
        this.setCrouseIsClick();
      },
      immediate: true
    }
  },
  computed: {
    version: function () {
      let version = '';
      this.syncCatalogList.some(item => {
        if (item.id === this.bookId) {
          const infoObj = {};
          item.tags.some(tagItem => {
            infoObj[tagItem.tagId] = tagItem.enumName;
            infoObj[tagItem.tagId + 'Code'] = tagItem.enumCode;
          });
          this.coursestyleCode = infoObj.coursestyleCode ? infoObj.coursestyleCode : '';
          version = `${infoObj.edition ? infoObj.edition : ''}${infoObj.grade ? infoObj.grade : ''}${infoObj.volume ? infoObj.volume : ''}${infoObj.electivetype ? infoObj.electivetype : ''}`;
        }
      });
      return version;
    }
  },
  async created () {
     const userInitInfo = getJsonlocalStore('userInitInfo');
     if (userInitInfo) {
       this.currentInfo = {
         currentStageCode: userInitInfo.studentStageCode, // 当前学段编码
        currentGradeCode: userInitInfo.gradeCode, // 当前年级编码
        currentTermCode: userInitInfo.currentTermCode, // 当前学期编码
        currentSubjectCode: localStorage.getItem('currentSubjectCode') // 当前学科编码
       };
     }
     await this.getCourseData();
  },
  methods: {
    // 设置上一课、下一课是否可点击
    setCrouseIsClick () {
      if (this.couseData.length <= 1) {
        this.isLeftClick = false;
        this.isRightClick = false;
      } else {
        if (this.showCrouseIndex === 0) {
          this.isLeftClick = false;
          this.isRightClick = true;
        } else if (this.showCrouseIndex > 0 && this.showCrouseIndex === (this.couseData.length - 1)) {
          this.isLeftClick = true;
          this.isRightClick = false;
        } else {
          this.isLeftClick = true;
          this.isRightClick = true;
        }
      }
    },
    /**
     * @description: 上一课
     * @param {*}
     * @Author: ckk
     * @Date: 2022-10-24 15:23:06
     * @return {*}
     */
    toPerFun () {
      if (this.showCrouseIndex >= 1) {
        this.showCrouseIndex = this.showCrouseIndex - 1;
        this.showCourseObj = this.couseData[this.showCrouseIndex];
        const obj = { ...this.showCourseObj };
        this.changeCrouse(obj);
      }
    },
    /**
     * @description: 下一课
     * @param {*}
     * @Author: ckk
     * @Date: 2022-10-24 15:23:24
     * @return {*}
     */
    toNextFun () {
      if (this.showCrouseIndex < this.couseData.length - 1) {
        this.showCrouseIndex = this.showCrouseIndex + 1;
        this.showCourseObj = this.couseData[this.showCrouseIndex];
        const obj = { ...this.showCourseObj };
        this.changeCrouse(obj);
      }
    },
    // 整理代码
        // 获取目录下面的 环节或者资源
    async getCourseLinkData (item) {
      // 判断同步模块下面 直接添加的资源 还是 有环节有资源。
      // 如果是单个资源的话 直接播放  多个资源的时候 跳转到资源列表页面
      const params = { catalogueIds: item.sourceCode, type: 1, isNew: 0, isRecursive: 1 },
        res = await excellentServices.getCrouseRes(params);
      if (res && parseInt(res.data.type) === 1) {
        if (res.data.moduleVoList) {
        let title = item.sourceName.replace(/[\s]+/g, '-');
            title = item.sourceName.replaceAll('&', '|');
          YouXin.openWindow({
            // playScene 环节列表页面 播放场景 统计使用 syn表示同步课程进入播放  lession标识专项课程进入的播放
            url: `${window.hostOrigin}/stepslist?id=${item.sourceCode}&coursestyle=${this.coursestyleCode}&title=${encodeURI(title)}&syncCatId=${this.syncCatId}&bookId=${this.bookId}&fromType=openwindow&type=synctarin&playScene=sync`,
            showHeader: '0',
            screenMode: '1'
          });
        }
        return;
      }
      const resList = res.data.moduleVoList[0].resList;
      console.log(resList.length, 'resList');
      if (resList.length === 0 || !resList) {
        this.$toast('资源储备中~');
        return false;
      } else if (resList.length === 1) { // 只有单个资源 在这里进行播放
        this.play(resList[0], item.sourceCode, item.sourceName);
      } else { // 资源列表页
        // this.$router.push({ name: 'modulesourceList', query: { id: item.sourceCode, title: item.sourceName } });
        let title = item.sourceName.replace(/[\s]+/g, '-');
            title = item.sourceName.replaceAll('&', '|');
        YouXin.openWindow({
          url: `${window.hostOrigin}/modulesourceList?id=${item.sourceCode}&title=${encodeURI(title)}&syncCatId=${this.syncCatId}&bookId=${this.syncCatId}&fromType=openwindow&playScene=sync`,
          showHeader: '0',
          screenMode: '1'
        });
      }
    },
    // 获取目录下面的 环节或者资源
    gotoStudy: throttle(function (item) {
      this.getCourseLinkData(item);
    }, 2000, { leading: true, trailing: false }),
    // 切换课程
    changeCrouse (item) {
      this.currentId = item.id;
      // 向用户中心保存切换的目录id
      this.setCurrentCatalogId();
      this.getCrouseResData(item.id, item.isNew, true);
    },
    /**
     * @description: 切换目录
     * @param {*}
     * @Author: ckk
     * @Date: 2022-08-26 11:16:00
     * @return {*}
     */
     async switchDirectories () {
      await this.getCourseData();
      this.catalogueshow = true;
    },
    /**
     * @description: 关闭目录修改框
     * @param {*}
     * @Author: ckk
     * @Date: 2022-08-27 15:36:35
     * @return {*}
     */
    onDialogClose () {
      this.catalogueshow = false;
    },
    /**
     * @description: 切换版本
     * @param {*}
     * @Author: ckk
     * @Date: 2022-08-27 16:04:21
     * @return {*}
     */
    onVersionSwitch () {
      this.$router.push({ name: 'bookVersoin' });
    },
    /**
     * @description: 切换课程
     * @param {*}
     * @Author: ckk
     * @Date: 2022-08-27 16:08:24
     * @return {*}
     */
    async onTreeSelect (item) {
      this.showCourseObj = item;
      this.currentId = item.id;
      // 向用户中心保存切换的目录id
      await this.setCurrentCatalogId();
      await this.getCrouseResData(item.id, item.isNew, true);
    },
    // 获取用户最新进度
    async getUserCatalogId (bookId) {
      const res = await catalogServices.getUsedCatalog(bookId); // /user/book/progress/
      return res.data.catalogId;
    },
    // 用户中心保存当前进度
    async setCurrentCatalogId () {
      await catalogServices.updateUseCatalog(this.bookId, this.currentId);
    },
    // 获取课程
    async getCourseData (getBookIdFlag) {
      // ,volume-${that.currentInfo.currentTermCode}
      // 获取当前选择的版本
      if (!getBookIdFlag) {
        const param = {
          studyStageCode: this.currentInfo.currentStageCode,
          gradeCode: this.currentInfo.currentGradeCode,
          subjectCode: this.currentInfo.currentSubjectCode
        };
        if (this.currentInfo.currentStageCode !== '0003') {
          param.termCode = this.currentInfo.currentTermCode;
        }
        const bookRecord = await excellentServices.studentGetBookId(param);
        try {
          this.bookId = bookRecord.data.bookId;
        } catch (error) {
        }
      }
      const that = this,
        tagstr = that.currentInfo.currentStageCode === '0003' ? `section-0003,subject-${that.currentInfo.currentSubjectCode}` : `section-${that.currentInfo.currentStageCode},grade-${that.currentInfo.currentGradeCode},volume-${that.currentInfo.currentTermCode},subject-${that.currentInfo.currentSubjectCode}`,
        params = { tags: tagstr, pageNum: 1, pageSize: 100, status: 1 },
        res = await excellentServices.getCrouseList(params); // /catalogue/list_course
        that.syncCatalogList = res.data.syncList || [];
        this.getCourseReady = true;
      // 如果有同步课程
      if (that.syncCatalogList.length > 0) {
        // 获取所有的版本信息 用于切换信息
        const versionArr = that.stuHomeEdiFormat(that.syncCatalogList, []),
          versionObj = {};
          // 12.23 libaochuan
        // 根据获取的 进度里面的bookId 定位当前版本
          // 根据获取的 进度里面的bookId 定位当前版本
        let parentId = '',
          childId = '',
          prevBookObj = versionArr.find(item => {
            // 根第一层id 匹配到 说明只有一层版本
            if (item.itemCode === this.bookId) {
              parentId = item.itemCode;
              childId = this.bookId;
              return true;
            }
            // 如果存在二级版本的时候，则说明根据 获取用户保存的版本 与 第二层版本匹配，
            if (item.childList) {
              let flag = false;
              item.childList.some(innerItem => {
                if (innerItem.itemCode === this.bookId) {
                  parentId = item.itemCode;
                  childId = this.bookId;
                  flag = true;
                  return true;
                }
              });
              return flag;
            }
          });
        if (!prevBookObj) {
          prevBookObj = versionArr[0];
          versionObj.versionArr = versionArr;
          versionObj.activeVersion = prevBookObj.itemCode;
          versionObj.semester = prevBookObj.childList ? prevBookObj.childList[0].itemCode : '';
          if (versionObj.semester) {
            this.bookId = versionObj.semester;
          } else {
            this.bookId = versionObj.activeVersion;
          }
          local.set('version', JSON.stringify(versionObj));
        } else {
          versionObj.versionArr = versionArr;
          versionObj.activeVersion = parentId;
          versionObj.semester = prevBookObj.childList ? childId : '';
          local.set('version', JSON.stringify(versionObj));
        }
        // 获取当前课程的对应的环节展示模板方式、
        if (!that.refreshFlag) { // 第一次请求的时候
          let syncObj = that.syncCatalogList.find(item => {
            return item.id === this.bookId;
          });
          if (!syncObj) {
            syncObj = that.syncCatalogList[0];
          }
          // 获取info 设置bookId 版本信息。二楼资源制作需要使用
          // const info = JSON.parse(local.get('info'));
          // info.version = syncObj.id;
          // local.set('info', JSON.stringify(info));
          that.refreshFlag = false;
          that.crouseType = syncObj.type;
          that.courseIsNew = syncObj.isNew;
          // 根据版本 获取 专项课程；专项课程和
          this.getListSubjectSpecial();
        }
        // 根据当前第一个课程的类型获取目录
        if (that.crouseType === 4) {
          // 获取同步培优模块
          this.getSyncCrouseTreeData(that.bookId, that.courseIsNew);
        }
      } else {
        this.getListSubjectSpecial();
      }
    },
    stuHomeEdiFormat (course = [], arr = []) {
      const taget = [];
      course.forEach(item => {
        item.tags && item.tags.forEach(v => {
          if (v.tagId === 'edition') {
            const obj = Object.assign({}, v, { tags: item.tags });
            obj.fileUrl = item.fileUrl;
            obj.boId = item.id;
            taget.push(obj);
          }
        });
      });
      const arys = [];
      taget.forEach(item => {
        if (!arys.includes(item.enumCode)) {
          arr.push(item);
        } else {
          const num = arr.findIndex(h => h.enumCode === item.enumCode);
          arr[num].tags = arr[num].tags.concat(item.tags);
        }
        arys.push(item.enumCode);
      });
      arr.forEach(item => {
        item.tags.forEach(v => {
          if (v.tagId === 'electivetype') {
            if (item.childList) {
              item.childList.push(v);
            } else {
              item.childList = [v];
            }
          }
        });
      });
      return arr;
    },
    // 学科专项内容列表接口
    async getListSubjectSpecial () {
      const params = {
        section: this.currentInfo.currentStageCode,
        grade: this.currentInfo.currentGradeCode,
        subject: this.currentInfo.currentSubjectCode,
        version: this.bookId
      };
      if (this.currentInfo.currentStageCode !== '0003') {
        params.volume = this.currentInfo.currentTermCode;
      }
      const res = await excellentServices.getListSubjectSpecial(params); // /catalogue/list_course
      this.getSpecialListReady = true;
      this.specialList = res.data || [];
    },
    // 获取同步培优课程目录  根据bookId
    async getSyncCrouseTreeData (bookId, isNew) {
      const that = this,
        params = { bookId: bookId, isNew: isNew },
        res = await excellentServices.getSyncCrouseTree(params); // catalogue/list_sync_course
      that.catalogTree = res.data.childList || [];
      that.treeData = res.data;
      this.$nextTick(() => {
        if (this.$refs.cataDialog.$refs.Catalogue) {
          this.$refs.cataDialog.$refs.Catalogue.treeData = this.treeData;
        }
      });
      if (that.catalogTree.length === 0) {
        this.syncModleList = []; // 同步模块职位空数组
      }
      // // 获取目录书中所有叶子节点集合
      console.log(that.catalogTree, 'siou');
      const cataArr = findTreeLeaf(that.catalogTree, []);
      that.couseData = cataArr;
      const couseDataLength = that.couseData.filter(item => item.id === that.currentId);
      console.log(couseDataLength, 'couseDataLength', that.couseData[0]);
      that.showCourseObj = couseDataLength.length > 0 ? couseDataLength[0] : that.couseData[0];
      that.showCrouseIndex = this.couseData.findIndex(v => v.id === this.currentId) > 0 ? this.couseData.findIndex(v => v.id === this.currentId) : 0;
      // 获取用户目录当前进度
      // currentId 不为空，且当前不是 切换年级引起的刷新
      if (that.currentId !== '' && !this.switchGrade) { // 处理切换上一课下一课然后进入环节或资源列表 但是不点击资源 异常
        that.getCrouseResData(that.currentId, '1', false);
      } else {
        this.switchGrade && this.SET_SWITCHGRADE(false);
        that.getUserCatalogId(bookId).then(res => {
          // 最新进度无数据或在目录树上找不到，默认展示目录树上第一个叶子节点
          if (!res || findTreeNodeById(that.catalogTree, [], res).length < 1) {
            if (cataArr[0]) {
              that.currentId = cataArr[0].id;
              that.catalogId = cataArr[0].id;
              that.getCrouseResData(cataArr[0].id, cataArr[0].isNew, true);
            } else {
              that.moduleInfo = {};
            }
          } else {
            const redObj = findTreeNodeById(that.catalogTree, [], res)[0];
            that.currentId = redObj.id;
            that.catalogId = redObj.id;
            that.getCrouseResData(redObj.id, redObj.isNew, false);
          }
        });
      }
    },
    // 获取课程下的模块
    async getCrouseResData (catalogId, isNew, isInt) {
      const that = this,
        params = { catalogueIds: catalogId, type: 1, isNew: that.courseIsNew === 0 ? 0 : isNew, isRecursive: 0 },
        res = await excellentServices.getCrouseRes(params); // /catalogue/list_res
      that.moduleInfo = JSON.parse(JSON.stringify(res));
      if (res.code === '200') {
        this.syncModleList = res.data.tagCourseContentVoList;
      }
      that.ResListFormt(that.moduleInfo);
      // // 埋点
      // PVCollector.getNormalStaticParam(PVCollector.STU_EVENT_ID.RMS_COURSE_SYNC_SUBJECT, { calInfo: { catalogueId: this.catalogId, bookId: this.bookId } });
    },
    // 遍历模块下的资源获取资源id字符串
    ResListFormt (moduleInfo) {
      const that = this;
      if (moduleInfo.type === '0') {
        if (moduleInfo.resList && moduleInfo.resList.length > 0) {
          const resArr = moduleInfo.resList;
          let resIds = [];
          resIds = resArr.map(v => v.destCode);
          resArr.forEach(v => {
            if (v.paperList && v.paperList.length > 0) {
              resIds = resIds.concat(v.paperList.map(h => h.destCode));
            }
          });
          that.getCrouseResRecordData(resIds.toString());
        }
      } else {
        if (moduleInfo.moduleVoList) {
          const arr = JSON.parse(JSON.stringify(moduleInfo.moduleVoList));
          let ids = [];
          arr.forEach(v => {
            if (v.resList && v.resList.length > 0) {
              ids = ids.concat(v.resList.map(h => h.destCode));
              v.resList.forEach(t => {
                if (t.paperList && t.paperList.length > 0) {
                  ids = ids.concat(t.paperList.map(h => h.destCode));
                }
              });
            }
            if (v.linkVoList) {
              const linkArr = JSON.parse(JSON.stringify(v.linkVoList));
              linkArr.forEach(h => {
                if (h.resList && h.resList.length > 0) {
                  ids = ids.concat(h.resList.map(t => t.destCode));
                  h.resList.forEach(g => {
                    if (g.paperList && g.paperList.length > 0) {
                      ids = ids.concat(g.paperList.map(y => y.destCode));
                    }
                  });
                }
              });
            }
          });
          that.getCrouseResRecordData(ids.toString());
        }
      }
    },
    play (item, stepCode, parentName) {
      item.sourceCode = stepCode;
      const playParam = assemblePlayParams(item, 'syncLearn');
      playParam.parentName = parentName;
      playParam.playScene = 'sync';
      judgePlay(playParam, item).then((value) => {
        if (Number(item.destType) === 5 || Number(item.destType) === 13 || Number(item.destType) === 2) { // 如果是应用的话 不需要上传进度
          return;
        }
        const parmas = {
          catId: stepCode,
          resId: item.destCode,
          resType: 1,
          purpose: 4,
          spendTime: value.obj && value.obj.currentTime,
          duration: value.finish || value
        };
        if (item.sourceFormat === 'F300' && Number(value.finish) === 100) {
          commitTask({ catId: item.stepCode });
        }
        this.addRecord(parmas);
      });
    },
        // 获取资源学习进度
    async getCrouseResRecordData (ids) {
      const that = this,
        params = { resIds: ids, purpose: 5, size: 100 },
        res = await excellentServices.getResRecords(params);
      that.resRecordData = JSON.parse(JSON.stringify(res));
    }
  }
};
</script>

<style scoped lang="scss">
.synchronization{
  margin-bottom:16px;
  padding:0 16px;
}
.sync-top{
  height: 120px;
  margin-top:10px;
  position: relative;
  background: #c4c4c4;
  border-radius: 10px;
  .studyone{
    width:auto;
    height: 50px;
    position: absolute;
    left:0;
    top:0px;
  }
  img{
      width:100%;
      height:100%;
  }
  .link{
    width:307px !important;
    height: auto;
    margin:0 auto;
    margin-top:12px;
    display: block;
  }
  .sync-content{
      position: absolute;
      left:0;
      top:0;
      height: 120px;
      width:100%
  }
}
.catalogue{
  display: flex;
  align-items: center;
  padding-right:27px;
  padding-top:13px;
  font-size: 14px;
  font-weight: 800;
  color: #FFFFFF;
  justify-content: flex-end;
  img{
  width:20px;
  height: 20px;
  margin-right:5px;
  }
}
.course-name{
  font-size: 16px;
  font-weight: 800;
  padding-left:26px;
  color: #FFFFFF;
  padding-top:9px;
}
.check-course{
  margin-top:6px;
  display: flex;
  justify-content: space-between;
  padding:0 26px;
  align-items: center;
  font-size: 12px;
  font-weight: 400;
  color: #FFFFFF;
  .btns{
      display: flex;
      align-items: center;
      img{
          width:44px;
          height: 26px;
      }
  }
}
.sync-bottom{
  min-height: 100px;
  background: #FFFFFF;
  border-radius: 10px;
  margin-top:10px;
  padding:10px 0;
  padding-bottom:20px;
  .sync-item{
    font-size: 14px;
  font-weight: 500;
  color: #000000;
  padding-bottom:10px;
  .sync-title{
      padding:16px;
  }
  }
  .description{
    padding:0 16px;
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
  img{
    width: 48px;
    height: 48px;
  }
  p{
    font-size: 12px;
    font-weight: 400;
    color: rgba(0,0,0,0.65);
    margin-top:6px;
    text-align: center;
  }
  }
  .description-item{
    // margin-right:8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width:25%;
    margin-bottom:10px;
  }
}
</style>
